package com.llk.yz.view;

import hdx.pwm.PWMControl;

import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.camera.api.CameraManager;
import com.llk.util.Config;
import com.llk.util.NetworkTool;
import com.ruanneng.camera.StreamIt;
public class MipcaActivityCapture extends Activity implements SurfaceHolder.Callback {
	private int newVerCode = 0;
	private String newVerName = "";
	NotificationManager nm;


	SurfaceView sView;
	SurfaceHolder surfaceHolder;
	int screenWidth, screenHeight;	
	Camera camera;                    
	boolean isPreview = false;        
	private StreamIt barcode = new StreamIt();

	//弹框显示信息
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			if (msg.what == R.id.sView) {
				String strcode = barcode
						.decode((byte[]) msg.obj, msg.arg1, msg.arg2);
				writeFileSdcard("mnt/sdcard/IMG_008.jpg="+Integer.toString(msg.arg1)+"="+Integer.toString(msg.arg2)+"=.dat",(byte[])msg.obj);
				if (strcode.length() > 0) {
					PWMControl.EnableBuzze(1);
					Intent resultIntent = new Intent(MipcaActivityCapture.this,FinishActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("result", strcode);
					bundle.putString("mode","1");
					resultIntent.putExtras(bundle);
					startActivity(resultIntent);
					SystemClock.sleep(100);
					PWMControl.EnableBuzze(0);
				}
			}
		}
	};
	// 写文件
	public final static void writeFileSdcard(String fileName, byte [] bytes){ 
		try{ 
			//FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
			FileOutputStream fout = new FileOutputStream(fileName);
			fout.write(bytes); 
			fout.close(); 
		} 
		catch(Exception e){ 
			e.printStackTrace(); 
		} 
	}

	public void showSet(){
		final AlertDialog.Builder ad=new AlertDialog.Builder(this);
		ad.setTitle("提示");
		ad.setMessage("是否设置网络?");
		ad.setPositiveButton("是", new DialogInterface.OnClickListener() {//退出按钮
			@Override
			public void onClick(DialogInterface dialog, int i) {
				// TODO Auto-generated method stub
				startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
			}

		});
		ad.setNegativeButton("否",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int i) {
				dialog.dismiss();
			}
		});
		ad.show();//显示对话框
	}

	public void showUpdate(){
		AlertDialog.Builder ad=new AlertDialog.Builder(this);
		ad.setTitle("提示");
		ad.setMessage("是否升级到最新程序?");
		ad.setPositiveButton("是", new DialogInterface.OnClickListener() {//退出按钮
			@Override
			public void onClick(DialogInterface dialog, int i) {
				// TODO Auto-generated method stub
				Intent resultIntent = new Intent(MipcaActivityCapture.this,UpdateActivity.class);
				startActivity(resultIntent);
			}

		});
		ad.setNegativeButton("否",new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int i) {
				dialog.dismiss();
			}
		});
		ad.show();//显示对话框
	}

	/**
	 * 判断Network是否开启(包括移动网络和wifi)
	 * @return
	 */
	public boolean isNetworkEnabled() {
		ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);  
		if (connectivity != null)  
		{  
			NetworkInfo[] info = connectivity.getAllNetworkInfo();  
			if (info != null)  
				for (int i = 0; i < info.length; i++)  
					if (info[i].getState() == NetworkInfo.State.CONNECTED)  
					{  
						return true;  
					}  
		}  
		return false; 
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_main);
		TextView titleView=(TextView) findViewById(R.id.textview_title);
		titleView.setText("刷码验证");
		if(isNetworkEnabled()==false){
			showSet();
		}

		CameraManager.init(getApplication());
		barcode.init(this);


		sView = (SurfaceView) findViewById(R.id.sView);                  		
		surfaceHolder = sView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		nm=(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);


		//检测版本
		new Thread(
				new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (getServerVerCode()) {
							int vercode = Config.getVerCode(MipcaActivityCapture.this);
							Log.d("newVerCode", newVerCode+"");
							if (newVerCode > vercode) {
								MipcaActivityCapture.this.runOnUiThread(new Runnable() {
									public void run() {
										showUpdate();
										//显示通知栏更新
										//showNotification(R.drawable.notification, "系统有新版本可以升级", "系统升级", "当前系统已有新版版，赶快更新吧");
									}
								});
								//显示通知栏更新
								//showNotification(R.drawable.notification, "系统有新版本可以升级", "系统升级", "当前系统已有新版版，赶快更新吧");
							}
						}
					}
				}
				).start();

		//辅助码验证
		Button codeCheck=(Button)findViewById(R.id.button1);
		codeCheck.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent resultIntent = new Intent(MipcaActivityCapture.this,CodeActivity.class);
				startActivity(resultIntent);
			}
		});

		Button logButton=(Button)findViewById(R.id.button2);
		logButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent resultIntent = new Intent(MipcaActivityCapture.this,LogActivity.class);
				startActivity(resultIntent);
			}
		});
	}

	private long exitTime = 0; 
	@Override  
	public boolean onKeyDown(int keyCode, KeyEvent event) {   
		if(keyCode == KeyEvent.KEYCODE_BACK    
				&& event.getAction() == KeyEvent.ACTION_DOWN){      
			return true;      
		}   
		return super.onKeyDown(keyCode, event);   
	}  

	public boolean getServerVerCode() {
		try {
			String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
					+ Config.UPDATE_VERJSON);
			JSONArray array = new JSONArray(verjson);
			if (array.length() > 0) {
				JSONObject obj = array.getJSONObject(0);
				try {
					newVerCode = Integer.parseInt(obj.getString("verCode"));
					newVerName = obj.getString("verName");
				} catch (Exception e) {
					newVerCode = -1;
					newVerName = "";
					return false;
				}
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	@Override
	protected void onDestroy() {
		barcode.deinit();
		super.onDestroy();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		try {
			CameraManager.get().openDriver(holder);
		} catch (IOException e) {
			CameraManager.get().closeDriver();
		}

		CameraManager.get().startPreview();
		GetImage();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		CameraManager.get().stopPreview();
		CameraManager.get().closeDriver();
	}

	private void GetImage() {
		new Thread() {
			public void run() {
				while (true) {
					CameraManager.get().requestPreview(mHandler, R.id.sView); // 请求预览获取图像数据
					CameraManager.get().requestAutoFocus(mHandler, 0); // 自动对焦
					SystemClock.sleep(200);
				}
			};
		}.start();
	}

	public void showNotification(int icon,String tickertext,String title,String content){  
		//设置一个唯一的ID，随便设置  
		//Notification管理器  
		Notification notification=new Notification(icon,tickertext,System.currentTimeMillis());  
		notification.defaults=notification.DEFAULT_LIGHTS;
		//后面的参数分别是显示在顶部通知栏的小图标，小图标旁的文字（短暂显示，自动消失）系统当前时间（不明白这个有什么用）  
		//这是设置通知是否同时播放声音或振动，声音为Notification.DEFAULT_SOUND  
		//振动为Notification.DEFAULT_VIBRATE;  
		//Light为Notification.DEFAULT_LIGHTS，在我的Milestone上好像没什么反应  
		//全部为Notification.DEFAULT_ALL  
		notification.flags=Notification.FLAG_AUTO_CANCEL;
		PendingIntent pt=PendingIntent.getActivity(this, 0, new Intent(this,UpdateActivity.class), 0);  
		//点击通知后的动作，这里是转回main 这个Acticity  
		notification.setLatestEventInfo(this,title,content,pt);  
		nm.notify(0,notification);  
	}
	//初始化摄像头
}